﻿using Abp.AutoMapper;
using Abp.Dependency;
using Abp.Events.Bus.Handlers;
using Abp.ObjectMapping;
using HCD.Events;
using HCD.Messages.Dtos;
using Microsoft.AspNetCore.SignalR;
using System.Linq;

namespace HCD.Web.Hubs
{
    /// <summary>
    /// 事件总线的消息处理器
    /// </summary>
    public class MsgPushHandler : IEventHandler<MsgPushEventData>, ITransientDependency
    {
        public IObjectMapper ObjectMapper { get; set; }
        private readonly IHubContext<SystemHub> _hubContext;
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="HubContext"></param>
        public MsgPushHandler(IHubContext<SystemHub> HubContext)
        {
            _hubContext = HubContext;
        }
        /// <summary>
        /// 事件处理
        /// </summary>
        /// <param name="eventData"></param>
        public void HandleEvent(MsgPushEventData eventData)
        {
            var dto = ObjectMapper.MapTo<MessageListDto>();
            var pool = SystemHub.Pool.ToLookup(v => v.Value);
            foreach (var g in pool)
            {
                if (eventData.MsgType == Enums.MsgTypeEnum.Chat)
                {
                    foreach (var item in g)
                    {
                        if (item.Value != dto.SenderID)
                            _hubContext.Clients.Client(item.Key).SendAsync("getChat", dto);
                    }
                }
                else
                {
                    if (eventData.Receiverids.Contains(g.Key))
                    {
                        foreach (var item in g)
                        {
                            _hubContext.Clients.Client(item.Key).SendAsync("getItem", dto);
                        }
                    }
                }
            }
        }
    }
}
